﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectSecurityDepositRepository : Repository<ProjectSecurityDeposit, DefaultDbContext>
    {
        public ProjectSecurityDepositRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public IPagedList<ProjectSecurityDeposit> GetProjectSecurityDeposits(ProjectSecurityDepositQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("project_security_deposit");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or code Like @0 or refund_corp_name Like @0 or refund_corp_code Like @0 or instrument_number Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");

            if (query.ProjectId.HasValue)
                sql.Where("project_id=@0", query.ProjectId);
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public ProjectSecurityDeposit? GetProjectSecurityDepositByMaxSerialNumber(DateTime time, int projectId)
        {
            Sql sql = Sql.Builder.Select("id").From("project_security_deposit");
            sql.Where("DATE(create_time)=@0", time.Date);
            sql.Where("project_id=@0", projectId);
            sql.OrderBy("serial_number desc");
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }
    }
}